package com.superlc.ssm.core.aop;


import com.superlc.ssm.common.util.RequestInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author super
 */
@Aspect
@Component
public class LogAspect {

    protected  static Logger logger = LoggerFactory.getLogger("Controller日志");

    @Pointcut("@annotation(com.superlc.ssm.core.common.annotation.Log)")
    //@Pointcut("within(com.superlc.ssm.modular.sys.controller.*)")
    //@Pointcut("execution(public * com.superlc.ssm.modular.sys.controller.ApiController.*(..))")
    public void requestLog(){//Api请求的切入点

    }

    @Before("requestLog()")
    public void deBefore(JoinPoint joinPoint) throws Throwable{
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容

        logger.info(new RequestInfo(request.getRequestURL().toString(),
                request.getRemoteAddr(),
                request.getMethod(),
                joinPoint.toString(),
                Arrays.toString(joinPoint.getArgs())).toString());
    }

    @AfterReturning(value="requestLog()",returning = "result")
    public void afterReturning(JoinPoint joinPoint,Object result){
        logger.info(result.toString());
    }


}
